package main

import (
	"context"
	"errors"
	"fmt"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"

	"golang.org/x/sync/errgroup"
)

type Server string

func (server Server) ServeHttp(w http.ResponseWriter, req *http.Request) {
	fmt.Fprint(w, "hello world.\n\t", req)
}

func main() {
	svr := Server("server")
	http.HandleFunc("/", svr.ServeHttp)
	http.ListenAndServe("localhost:1234", nil)

	g, ctx := errgroup.WithContext(context.Background())
	g.Go(func() error {
		fmt.Println("http")
		go func() {
			<-ctx.Done()
			fmt.Println("Server handle down")
		}()
		return nil
	})

	g.Go(func() error {
		exitSignals := []os.Signal{os.Interrupt, syscall.SIGTERM, syscall.SIGQUIT, syscall.SIGINT}
		sig := make(chan os.Signal, len(exitSignals))
		signal.Notify(sig, exitSignals...)
		for {
			fmt.Println("handle signal")
			select {
			case <-ctx.Done():
				fmt.Println("signal ctx done")
				return ctx.Err()
			case <-sig:
				fmt.Println("handle signal")
				return nil
			}
		}
	})

	//simulate error
	g.Go(func() error {
		fmt.Println("error")
		time.Sleep(2 * time.Second)
		return errors.New("error")
	})

	if error := g.Wait(); error != nil {
		fmt.Print(error)
	} else {
		fmt.Println("No Error Happened.")
	}
}
